import { AutoComplete, Col, Empty, Input, Menu } from 'antd';
import { ChangeEvent, useContext, useEffect, useMemo } from 'react';
import { IAuthSecondLeftTree } from '../../type';
import { AuthorizationContext } from '../AuthHooks';
import { SearchOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import MyIcon from '@/components/MyIcon';
import { loopArray } from '@/utils';
import _ from 'lodash';

export const AuthThreeLeftTree: React.FC<IAuthSecondLeftTree> = ({
  secondLeftTree,
  onMenuSelectChange,
}) => {
  const {
    prefixCls,
    threeLeftSearValue,
    threeMenuCheckKeys,
    authGranDispatch,
    threeMenuOpenKeys,
  } = useContext(AuthorizationContext); //获取 上下文

  useEffect(() => {
    if (secondLeftTree?.[0]?.id) {
      authGranDispatch({
        type: 'authGran-threeMenuOpenKeys',
        payload: [secondLeftTree?.[0]?.id],
      });
      authGranDispatch({
        type: 'authGran-threeMenuCheckKeys',
        payload: [secondLeftTree?.[0]?.id],
      });
      onMenuSelectChange(false, secondLeftTree?.[0]);
    }
  }, [secondLeftTree?.[0]?.id]);

  // 处理 menu菜单
  // const handleMenu = (list: any[]) => {
  //   return list?.map((item: any, index: number) => {
  //     const name = item?.name ?? item?.text;
  //     const nameLength = name?.length;
  //     const select = name?.search(threeLeftSearValue);
  //     const searchLength = threeLeftSearValue?.length;
  //     const afterStr = name?.slice(0, select);
  //     const selectStr = threeLeftSearValue;
  //     const beforeStr = name?.slice(select + searchLength, nameLength);
  //     const titleTree =
  //       select > -1 && selectStr ? (
  //         <>
  //           {afterStr}
  //           <span style={{ color: '#f50' }}>{selectStr}</span>
  //           {beforeStr}
  //         </>
  //       ) : (
  //         <>{item?.name ?? item?.text ?? '--'}</>
  //       );

  //     if (item?.resourceType == 1 || item?.textType == 1) {
  //       return (
  //         <Menu.Item
  //           key={item?.id}
  //           id={item?.id + 'left'}
  //           icon={<MyIcon type={item?.icon} style={{ marginRight: 5 }} />}
  //           itemRef={item}
  //         >
  //           {titleTree}
  //         </Menu.Item>
  //       );
  //     }
  //     if (item?.resourceType == 0 || item?.textType == 0) {
  //       return (
  //         <Menu.SubMenu
  //           key={item?.id}
  //           title={titleTree}
  //           icon={<MyIcon type={item?.icon} style={{ marginRight: 5 }} />}
  //           onTitleClick={(e) => {
  //             let subMenuObj: any = {
  //               item: item,
  //               key: e?.key,
  //             };
  //             menuClick(subMenuObj, true);
  //           }}
  //         >
  //           {item?.children &&
  //             item?.children?.length > 0 &&
  //             handleMenu(item?.children)}
  //         </Menu.SubMenu>
  //       );
  //     }
  //   });
  // };

  // 搜索下拉菜单
  const autoOptionLeft = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if ((item?.text || item?.name)?.includes(threeLeftSearValue)) {
          // const name = item?.text || item?.name;
          // const nameLength = name?.length;
          // const select = name?.search(threeLeftSearValue);
          // const searchLength = threeLeftSearValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = threeLeftSearValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.text || item?.name,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
          });
        }
      });
    };
    tileTreeData(secondLeftTree);
    return option;
  }, [secondLeftTree, threeLeftSearValue]);

  // 点击菜单调用
  const menuClick = (paramObj: any, type: boolean) => {
    if (type) {
      authGranDispatch({
        type: 'authGran-threeMenuOpenKeys',
        payload: [paramObj?.key],
      });
      onMenuSelectChange(false, paramObj?.item);
    } else {
      authGranDispatch({
        type: 'authGran-threeMenuCheckKeys',
        payload: [paramObj?.key],
      });
      onMenuSelectChange(false, paramObj?.item?.props?.itemRef);
    }
  };

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    authGranDispatch({
      type: 'authGran-threeLeftSearValue',
      payload: e.target.value,
    });
  };

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve, reject) => {
      const optionId = option?.key;
      const targetNode: any = loopArray(secondLeftTree)?.find(
        (i) => i?.id == optionId,
      );

      authGranDispatch({
        type: 'authGran-secondMenuOpenKeys',
        payload: [targetNode?.pID],
      });

      if (targetNode?.textType == '1' || targetNode?.resourceType == '1') {
        authGranDispatch({
          type: 'authGran-threeMenuCheckKeys',
          payload: [optionId],
        });
      }
      authGranDispatch({
        type: 'authGran-threeLeftSearValue',
        payload: value,
      });

      onMenuSelectChange(false, targetNode);

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
      }
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + '-threeLeft');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  /** 角色授权第三步功能操作 Menu 菜单  V4.24.8 */
  const funcOperaMenuItems = useMemo(() => {
    let menuList: any[] = _.cloneDeep(secondLeftTree);
    const loopMenuTree = (treeList: Record<string, any>[]) => {
      treeList?.forEach((item: any, index: number) => {
        const name = item?.name ?? item?.text;
        const nameLength = name?.length;
        const select = name?.search(threeLeftSearValue);
        const searchLength = threeLeftSearValue?.length;
        const afterStr = name?.slice(0, select);
        const selectStr = threeLeftSearValue;
        const beforeStr = name?.slice(select + searchLength, nameLength);
        const titleTree =
          select > -1 && selectStr ? (
            <>
              {afterStr}
              <span style={{ color: '#f50' }}>{selectStr}</span>
              {beforeStr}
            </>
          ) : (
            <>{item?.name ?? item?.text ?? '--'}</>
          );

        treeList[index] = {
          key: item?.id,
          label: (
            <span
              id={`${item?.id}-threeLeft`}
              style={{ width: '100%', display: 'inline-block' }}
              onClick={() => {
                if (
                  (item?.resourceType == 0 || item?.textType == 0) &&
                  !threeMenuOpenKeys?.includes(item?.id)
                ) {
                  let subMenuObj: any = {
                    item: item,
                    key: item?.id,
                  };
                  menuClick(subMenuObj, true);
                } else {
                  authGranDispatch({
                    type: 'authGran-threeLeftSearValue',
                    payload: '',
                  });
                }
              }}
            >
              <MyIcon type={item?.icon} style={{ marginRight: 5 }} />
              &nbsp;
              {titleTree}
            </span>
          ),
          itemRef: { ...item },
          children:
            item?.children && item?.children?.length > 0
              ? loopMenuTree(item?.children)
              : null,
        };
      });
      return treeList;
    };
    const newMenuList: any[] = loopMenuTree(menuList);
    return newMenuList;
  }, [secondLeftTree, threeLeftSearValue, threeMenuOpenKeys]);

  return (
    <>
      <Col span={6} className={prefixCls + 'step-cardRole-leftColMenu'}>
        <AutoComplete
          style={{ width: '100%', height: '5%' }}
          options={autoOptionLeft}
          notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
          onSelect={onAutoSelect}
        >
          <Input
            suffix={<SearchOutlined />}
            onChange={onInputChange}
            placeholder="请按名称搜索"
            allowClear={true}
            value={threeLeftSearValue ? threeLeftSearValue : undefined}
          />
        </AutoComplete>

        <ScrollBarLayout
          style={{
            padding: '10px',
            height: '95%',
          }}
        >
          <div
            style={{ paddingBottom: '10px' }}
            className={prefixCls + 'step-cardRole-secondLeftMenu'}
          >
            {secondLeftTree && secondLeftTree?.length > 0 ? (
              <>
                <Menu
                  mode="inline"
                  theme="light"
                  selectedKeys={threeMenuCheckKeys} //选中的 菜单
                  openKeys={threeMenuOpenKeys} //展开的 目录
                  items={funcOperaMenuItems}
                  onSelect={(itemObj: any) => {
                    menuClick(itemObj, false);
                  }}
                  onOpenChange={(openKeys: string[]) => {
                    authGranDispatch({
                      type: 'authGran-threeMenuOpenKeys',
                      payload: openKeys,
                    });
                    authGranDispatch({
                      type: 'authGran-threeMenuCheckKeys',
                      payload: [],
                    });
                  }}
                >
                  {/* {handleMenu(secondLeftTree)} */}
                </Menu>
              </>
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </div>
        </ScrollBarLayout>
      </Col>
    </>
  );
};
